package com.flca.frw.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SystemVarUtils
{
	private SystemVarUtils() {
	}

	/**
	 * This will replace all '$XXXX'  and/or '%XXXX%'  tags with the corresponding system properties
	 * if the corr system property is NOT found no change will be made
	 * @param aValue
	 * @return
	 */
	public static String replaceSystemVariables(String aValue)
	{
		String result = aValue;
		
		if (aValue.indexOf("$") >= 0)  {
			result = replaceDollarSysvar(aValue);
		} else if (aValue.indexOf("%") >= 0) {
			//TODO
		} 
		
		return result;
	}
	
	private static String replaceDollarSysvar(String aValue) 
	{
		String result = aValue;
		
		Pattern p = Pattern.compile("([\\w$][a-zA-Z_$]*)\\b");
		Matcher matcher = p.matcher(aValue);
		while (matcher.find()) {
			String token = aValue.substring(matcher.start(), matcher.end());
			if (token.startsWith("$")) {
				String subswith = System.getProperty(token.substring(1), token);
				subswith = subswith.replace("\"", "");
				result = result.replace(token, subswith);
			}
		}
		return result;
	}

}
